package cn.chencq.gdt.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.gdt.common.Constants;
import cn.chencq.gdt.vo.ProxyIp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.limei.adplatform.redis.cluster.RedisClusterFactory;

public class Utils {

	private static final Logger logger = LoggerFactory.getLogger(Utils.class);

	/**
	 * 生成请求rid
	 * 
	 * @return
	 */
	public static String generateRID() {
		String rid = System.currentTimeMillis() + "" + new Random().nextInt(10000);
		return rid;
	}

	/**
	 * md5
	 * 
	 * @param src
	 * @return
	 */
	public static String md5(String src) {
		byte[] md5Bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md5Bytes = md.digest(src.getBytes());
		} catch (Exception e) {
		}
		return Hex.encodeHexString(md5Bytes).toLowerCase();
	}

	// 通过网址获取host
	public static String getHost(String url) {
		String host = "";
		Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
		Matcher matcher = p.matcher(url);
		if (matcher.find()) {
			host = matcher.group();
		}
		return host;
	}

	// socketaddress网络代理
	public static Proxy setProxy(String ip, String port) {
		SocketAddress addr = new InetSocketAddress(ip, Integer.parseInt(port));
		Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
		return proxy;
	}

	/**
	 * 验证代理ip是否能正常使用
	 * 
	 * @param proxy
	 * @param website
	 * @return
	 */
	public static boolean verifyProxy(Proxy proxy, String website) {
		int code = HttpUtils.getResponeCode(website, proxy, null);
		if (code == 200) {
			return true;
		}
		return false;
	}

	/**
	 * 检验代理ip是否匿名
	 * 
	 * @param proxy
	 * @param website
	 * @return
	 */
	public static boolean checkIsAnnoy(Proxy proxy, String website) {
		// TODO
		return false;
	}

	public static int getNum(int start, int end) {
		return (int) (Math.random() * (end - start + 1) + start);
	}

	/**
	 * set 转成数组
	 * 
	 * @param set
	 * @return
	 */
	public static String[] setToArray(Set<String> set) {
		if (set != null && set.size() > 0) {
			String[] memebers = new String[set.size()];
			set.toArray(memebers);
			return memebers;
		}
		return null;
	}

	/**
	 * 随机生成电话号码
	 * 
	 * @return
	 */
	public static String getPhone() {
		String[] head = new String[] { "13", "15", "17", "18", "16" };
		Random rnd = new Random();
		String res = head[rnd.nextInt(head.length)];
		for (int i = 0; i < 9; i++) {
			res = res + rnd.nextInt(10);
		}
		return res;
	}

	/**
	 * 随机生成IMEI
	 * 
	 * @return
	 */
	public static String getIMEI() {
		int r1 = 1000000 + new java.util.Random().nextInt(9000000);
		int r2 = 1000000 + new java.util.Random().nextInt(9000000);
		String input = r1 + "" + r2;
		char[] ch = input.toCharArray();
		int a = 0, b = 0;
		for (int i = 0; i < ch.length; i++) {
			int tt = Integer.parseInt(ch[i] + "");
			if (i % 2 == 0) {
				a = a + tt;
			} else {
				int temp = tt * 2;
				b = b + temp / 10 + temp % 10;
			}
		}
		int last = (a + b) % 10;
		if (last == 0) {
			last = 0;
		} else {
			last = 10 - last;
		}
		return input + last;
	}
	
	/**
	 * 随机生成MAC
	 * 
	 * @return
	 */
	public static String getMAC() {
		String chars = "ABCDEF0123456789";
		String res = "";
		Random rnd = new Random();
		int leng = chars.length();
		for (int i = 0; i < 17; i++) {
			if (i % 3 == 2) {
				res = res + ":";
			} else {
				res = res + chars.charAt(rnd.nextInt(leng));
			}
		}
		return res;
	}

	/**
	 * 随机生成IMSI
	 * 
	 * @return
	 */
	public static String getImsi() {
		String title = "4600";
		int second = 0;
		do {
			second = new java.util.Random().nextInt(8);
		} while (second == 4);
		int r1 = 10000 + new java.util.Random().nextInt(90000);
		int r2 = 10000 + new java.util.Random().nextInt(90000);
		return title + "" + second + "" + r1 + "" + r2;
	}

	// 8-4-4-4-12 十六进制
	public static String getIdfa() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 8; i++) {
			Integer it = new Random().nextInt(16);
			sb.append(Integer.toHexString(it));
		}
		sb.append("-");
		for (int i = 0; i < 4; i++) {
			Integer it = new Random().nextInt(16);
			sb.append(Integer.toHexString(it));
		}
		sb.append("-");
		for (int i = 0; i < 4; i++) {
			Integer it = new Random().nextInt(16);
			sb.append(Integer.toHexString(it));
		}
		sb.append("-");
		for (int i = 0; i < 4; i++) {
			Integer it = new Random().nextInt(16);
			sb.append(Integer.toHexString(it));
		}
		sb.append("-");
		for (int i = 0; i < 12; i++) {
			Integer it = new Random().nextInt(16);
			sb.append(Integer.toHexString(it));
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * 随机生成网络ip
	 * 
	 * @return
	 */
	public static String getIP() {
		String chars = "0123456789";
		String res = "";
		Random rnd = new Random();
		int leng = chars.length();
		for (int i = 0; i < 4; i++) {
			int length = rnd.nextInt(3);
			if (length == 0) {
				length = 1;
			}
			String temp = "";
			for (int j = 0; j < length; j++) {
				temp = temp + chars.charAt(rnd.nextInt(leng));
			}
			res = res + Integer.parseInt(temp) + ".";
		}
		return res;
	}

	public static Set<ProxyIp> getProxyIpSet(int num) {
		Set<ProxyIp> sp = new HashSet<ProxyIp>();
		try {
			String resp = HttpUtils.getResponse(Constants.PROXY_URL + "?num=" + num, null, null);
			JSONObject json = JSON.parseObject(resp);
			int res = json.getInteger("res");
			if (res == 1) {
				JSONArray array = json.getJSONArray("proxylist");
				for (int i = 0; i < array.size(); i++) {
					JSONObject proxy = array.getJSONObject(i);
					sp.add(new ProxyIp(proxy.getString("ip"), proxy.getString("port")));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return sp;
	}

	public static ProxyIp getProxyIp() {
		ProxyIp proxyIp = null;
		try {
			String resp = HttpUtils.getResponse(Constants.PROXY_URL, null, null);
			JSONObject json = JSON.parseObject(resp);
			int res = json.getInteger("res");
			if (res == 1) {
				JSONArray array = json.getJSONArray("proxylist");
				if (array.size() > 0) {
					JSONObject proxy = array.getJSONObject(0);
					proxyIp = new ProxyIp(proxy.getString("ip"), proxy.getString("port"));
				}
			}
		} catch (Exception ex) {
			proxyIp = null;
		}
		return proxyIp;
	}

	// 2017052241298
	public static ProxyIp getProxyIpBy66() {
		ProxyIp proxyIp = null;
		try {
			String resp = HttpUtils.getResponse("http://www.66ip.cn/getzh.php?getzh=2017052241298&getnum=1&isp=0&anonymoustype=0&start=&ports=&export=&ipaddress=&area=1&proxytype=2&api=https", null, null);
			String regex = "((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9]):\\d{1,4}";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(resp);
			while (m.find()) {
				String proxy = m.group();
				String ip = proxy.split(":")[0];
				String port = proxy.split(":")[1];
				proxyIp = new ProxyIp(ip, port);
				logger.info(proxyIp.toString());
			}
		} catch (Exception ex) {

		}
		return proxyIp;
	}

	// tk代理
	public static Set<ProxyIp> getProxyIpByTk() {
		Set<ProxyIp> ps = null;
		try {
			String resp = HttpUtils.getResponse("http://api.tkdaili.com/api/getiplist.aspx?vkey=090787E49F2585A373DA538BC6B73A71&num=18&country=CN&high=1&style=7", null, null);
			ps = new HashSet<ProxyIp>();
			String[] arr = resp.split("\\|");

			Set<String> ips = new HashSet<String>();

			for (String s : arr) {
				String ip = s.split(":")[0];
				String port = s.split(":")[1];
				ps.add(new ProxyIp(ip, port));

				ips.add(s);
				logger.info(s);
			}

			if (ips.size() > 0) {
				RedisClusterFactory.sadd(Constants.CLUSTER, Constants.TK_PROXY, setToArray(ips));
			}

		} catch (Exception ex) {
			logger.error("fetch tk proxy throw exception:{}", ex);
		}
		return ps;
	}

	private static void addScanQueue(final String data) {
		try {
			new Thread(new Runnable() {
				@Override
				public void run() {
					StringBuilder sb = new StringBuilder();
					try {
						sb.append(Constants.SCAN_TASK_URL).append("?");
						sb.append("data=").append(URLEncoder.encode(data, "UTF-8"));
						String url = sb.toString();
						String resp = HttpUtils.getResponse(url, null, null);
						logger.error("ad tk proxy to scan queue,url:{}, http response:{}", url, resp);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}).start();
		} catch (Exception e) {
			logger.error("ad tk proxy to scan queue, throw exception:{}", e);
		}
	}

	/**
	 * 往文件里写内容
	 * 
	 * @param fileName
	 * @param text
	 */
	private static void appendToFile(String fileName, String text) {
		FileOutputStream fos = null;
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource(fileName).getPath();
			fos = new FileOutputStream(path, true);
			fos.write(text.getBytes());
			fos.write("\r\n".getBytes());
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
